//
//  HomeRefreshControl.swift
//  SinaWeibo
//
//  Created by 林柱强 on 16/2/9.
//  Copyright © 2016年 林柱强. All rights reserved.
//

import UIKit
import SnapKit

class HomeRefreshControl: UIRefreshControl {

    override init() {
        super.init()
        //1.初始化UI
        setupUI()
    }

    private func setupUI() {
        //1.添加子控件
        addSubview(refreshView)
        //2.布局子控件
        refreshView.xmg_AlignInner(type: XMG_AlignType.Center, referView: self, size: CGSizeMake(170, 60))
        
        /*
        1.当用户下拉到一定程度需要旋转箭头
        2.当用户上啦到一定程度需要旋转箭头
        3.当触发刷新方法时，需要显示刷新界面（转轮）
        */
        addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions.New, context: nil)
    }
    
    /// 记录是否提示要箭头
    private var rotationArrowFlag = false
    /// 记录是否执行圆圈动画
    private var loadingViewAnimFlag = false
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
//        print(frame.origin.y)
        
        //过滤掉不需要的数据
        if frame.origin.y >= 0 {
            
        }
        
        if refreshing && !loadingViewAnimFlag{
            //显示圈圈，并让圈圈执行动画
            refreshView.startloadingAnim()
            loadingViewAnimFlag = true
            return
        }
        
        if frame.origin.y > -50 && rotationArrowFlag{
            rotationArrowFlag = false
            refreshView.rotationArrowIcon(rotationArrowFlag)
        }else if frame.origin.y < -50 && !rotationArrowFlag{
            rotationArrowFlag = true
            refreshView.rotationArrowIcon(rotationArrowFlag)
        }
    }
    
    override func endRefreshing() {
        super.endRefreshing()
        
        //关闭圆圈动画
        refreshView.stoploadingAnim()
        
        //复位圆圈动画标记
        loadingViewAnimFlag = false
    }
    
    // MARK: 懒加载
    private lazy var refreshView: HomeRefreshView = HomeRefreshView.refreshView()
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        removeObserver(self, forKeyPath: "frame")
    }

}

class HomeRefreshView: UIView {
    
    @IBOutlet weak var arrowIcon: UIImageView!
    
    @IBOutlet weak var tipView: UIView!
    
    @IBOutlet weak var loadingView: UIImageView!
    
    func rotationArrowIcon(flag: Bool) {
        var angle = M_PI
        angle += flag ? -0.01 : 0.01
        UIView.animateWithDuration(0.2) { () -> Void in
            self.arrowIcon.transform = CGAffineTransformRotate(self.arrowIcon.transform, CGFloat(angle))
        }
    }
    /**
     开始圆圈动画
     */
    func startloadingAnim() {
        tipView.hidden = true
        
        let animation = CABasicAnimation(keyPath: "transform.rotation")
        //不移除动画
        animation.removedOnCompletion = false
        animation.repeatCount = MAXFLOAT
        animation.toValue = 2 * M_PI
        animation.duration = 0.5
        
        loadingView.layer.addAnimation(animation, forKey: nil)
    }
    /**
     停止圆圈动画
     */
    func stoploadingAnim() {
        tipView.hidden = false
        
        loadingView.layer.removeAllAnimations()
    }
    
    class func refreshView() -> HomeRefreshView {
        return NSBundle.mainBundle().loadNibNamed("HomeRefreshView", owner: nil, options: nil).last as! HomeRefreshView
    }
}